<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2016/12/26 0026
 * Time: 19:00
 */

namespace Home\Action;


use Think\Controller;

class AppClientAction extends BaseAction{

    public function index(){
        $this->display("default/appClient");
    }

    /**
     * 用途：获取首页广告列表
     * 输出格式：json
     * 输出结构:{[adId:广告Id  adName:广告名  adURL:广告链接  adFile: 广告图片路径],.......}
     */
    public function getIndexAd(){
        $today = date("Y-m-d");
        $adList = M("Ads")->field("adId,adFile,adName,adURL")->
        where(array("adStartDate"=>array("elt",$today),"adEndDate"=>array("egt",$today)))->order("adSort")->select();
        $this->ajaxReturn($adList);
    }

    /**
     * 用途：获取商铺类型列表
     * 输出格式：json
     * 输出结构:{[catId:类型Id  catName:类型名,catChidren:子类型],........}
     */
    public function getShopCategoryList(){
        $catList = M("GoodsCats")->field("catId,catName")->where("isShow = 1")->select();
        $this->ajaxReturn($catList);
    }


    /**
     * 用途：获取人气会员列表
     * @param $num  会员数量    传参方式：get   必须
     * 输出格式：json
     * 输出结构：{[userId:用户Id,userName:用户名,userSex:用户性别,userAge:年龄,userDesc:简介,userPhoto:头像],.....}
     */
    public  function getHotMember($num){
        $memberList = M("Users")->field("userId,userName,userSex,userAge,userDesc,userPhoto")->
        where(array("userStatus"=>1))->order("userScore desc")->limit($num)->select();
        $this->ajaxReturn($memberList);
    }




    /**
     * 用途：获取卖场商家列表
     * 传参方式：post
     * @param $pageNo   第几页         必须
     * @param $pageSize 分页大小    必须
     * @param $lat      当前位置纬度     必须
     * @param $lng      当前位置经度      必须
     * 输出格式：json
     * 输出结构：{[shopId:商铺Id,shopName:商铺名称,shopImg:商铺图片,distance:商铺距离],................}
     */
    public function getShopsList(){
        $shopCat = I("post.shopCat");
        $pageNo = I("post.pageNo")-1;
        $pageSize = I("post.pageSize");
        $lat = I("post.lat",22.84);
        $lng = I("post.lng",108.33);
        $sort = I("post.sort","distance");
        $sql = <<<EOT
SELECT
	a.shopId,
	a.shopName,
	a.shopImg,
	a.goodsCatId1,
	a.shopTel,
	a.shopAddress,
	a.latitude,
	a.longitude,
	a.mapLevel,
	a.star,
	a.visitNum,
	a.saleCount,
	a.createTime,
	b.areaName AS areaName1,
	c.areaName AS areaName2,
	d.areaName AS areaName3,
	getDistance(a.latitude, a.longitude, $lat, $lng) AS distance
FROM
	wst_shops a
LEFT JOIN wst_areas b ON a.areaId1 = b.areaId
LEFT JOIN wst_areas c ON a.areaId2 = c.areaId
LEFT JOIN wst_areas d ON a.areaId3 = d.areaId
WHERE
	a.shopFlag = 1
AND a.shopStatus = 1
AND a.goodsCatId1 = $shopCat
EOT;

        switch ($sort) {
            case "distance":
                $sql .= <<<EOT
	order by getDistance(a.latitude, a.longitude, $lat, $lng) asc
EOT;

                break;
            case "buzz":
                $sql .= " order by visitNum desc";
                break;
            case "saleCount":
                $sql .= " order by saleCount desc";
                break;
            case "new":
                $sql .= " order by createTime desc";
                break;

            default:
                break;
        }

        $sql .= "  LIMIT $pageNo,$pageSize";



        $shopList = M("Shops")->query($sql);

        $this->ajaxReturn($shopList);
    }


    /**
     * 获取商家商品
     */

    public function getGoodsListByShopId(){
        $shopId = I("post.shopId");
        $pageNo = I("post.pageNo") - 1;
        $pageSize = I("post.pageSize");

        $shopType = M("Shops")->where(array("shopId"=>$shopId))->getField("goodsCatId1");

        $sql = <<<EOT
SELECT
	a.goodsId,
	goodsName,
	goodsImg,
	goodsThums,
	marketPrice,
	shopPrice,
	monSaleCount,
	saleCount,
	goodsSpec,
	goodsDesc,
	startCity,
	startDate,
	roomSize,
	b.useTimeStart,
	b.useTimeEnd,
	b.periodStart,
	b.periodEnd,
	b.useRule,
	e.userName,
	c.content,
	c.createTime,
	(
		SELECT
			count(d.id)
		FROM
			wst_goods_appraises d
		WHERE
			d.goodsId = a.goodsId
	) AS cCount
FROM
	wst_goods a
LEFT JOIN wst_purchase_note b ON a.goodsId = b.goodsId
LEFT JOIN wst_goods_appraises c ON a.goodsId = c.goodsId
LEFT JOIN wst_users e ON c.userId = e.userId
WHERE
	goodsFlag = 1
AND goodsStatus = 1
AND a.shopId = $shopId
EOT;


        $goodsList = M()->query($sql);
		$Price = M("price");
		for($i = 0; $i < count($goodsList); $i++)
		{
			$p = $Price->where("goodsId = ".$goodsList[$i]['goodsId'])->select();
			$goodsList[$i]['prices'] = $p;
		}
        $this->ajaxReturn($goodsList);
    }



    /**
     * 获取跟团游行程列表
     */

    public function getScheduleList(){
        $travelTd = I("post.travelId");
        $scheduleList = M("ScheduleGoods")->where(array("travelId"=>$travelTd))->order("scheduleSort")->select();
        $this->ajaxReturn($scheduleList);
    }


    public function  sendSMS($code,$phone){



        return WSTSendSMS($phone,$code);
    }




    /**
     * 用途：验证手机号码是否已注册
     * @param $phone  手机号码
     * 输出格式：json
     * 输出结构  {status:0/1}    1  未注册
     */
    public function checkPhone($phone){
        $result = D("Home/Users")->checkLoginKey($phone);
       $this->returnAjax($result);
    }

    /**
     * 用途：用户注册
     * 输入参数：phone:手机号码   code：验证码   pwd：密码  uniuqId:
     * 传参方式：post
     * 输出：{status:状态码，msg:信息}  status = 0/1  失败/成功
     */
    public function registerUser(){
        $result["status"] = 0;
        $code = M("Code")->field("code,createTime")->where(array("uniuqId"=>I("post.uniuqId")))->find();
        if(IS_POST){
            $checkPhone = D("Home/Users")->checkLoginKey(I("post.phone"));
            if($checkPhone["status"] != 1){
                $result["msg"] = "该用户已注册";
            }else if(time() > strtotime('+5 min',intval($code["createTime"]))){
                $result["msg"] = "验证码超时";

            }else if(I("post.code") != $code["code"]){
                $result["msg"] = "验证码无效";
            }else{
               $data["loginName"] = I("post.phone");
                $data["userPhone"] = I("post.phone");
                $data["loginSecret"] = rand(1000,9999);
                $data['loginPwd'] = md5(I('post.pwd').$data['loginSecret']);
                $data["userFlag"] = 1;
                $data["userStatus"] = 1;
                if(!M("Users")->add($data)){
                    $result["msg"] = "注册错误";
                }else{
                    $result["status"] = 1;
                    $result["msg"] = "注册成功";
                }
            }

            $this->ajaxReturn($result);
        }
    }



    /**
     * 用途：获取短信验证码
     * 传参方式  get
     * @param $phone     手机号码
     * 输出格式：json
     * 输出结构  {status:0/1}    0代表短信发送失败
     */
    public function getPhoneCheckCode(){

        $phone = I("post.phone");
        $result["status"] = 0;
        $length = 4;
        $code = rand(pow(10,($length-1)), pow(10,$length)-1);
        if($this->sendSms($code,$phone)){
            $checkCode['code'] = $code;
            $checkCode['createTime'] = time();
            $checkCode["uniuqId"] = uniqid();
            M("Code")->add($checkCode);
            $result["status"] = 1;
            $result["uniuqId"] = $checkCode["uniuqId"];
        }
        $this->ajaxReturn($result);

    }

    /**\
     *用户登录
     * loginName
     * loginPwd
     */
    public function loginUser(){
        $rv = array('status'=>0);
        $loginName = I('post.loginName');
        $userPwd = I('post.loginPwd');

        $sql ="SELECT * FROM __PREFIX__users WHERE (loginName='".$loginName."' OR userEmail='".$loginName."' OR userPhone='".$loginName."') AND userFlag=1 and userStatus=1 ";

        $rss = M()->query($sql);



        if(!empty($rss)){
            $rs = $rss[0];
            if($rs['loginPwd']!=md5($userPwd.$rs['loginSecret'])){
                $rv["msg"] = "密码错误";
                $this->ajaxReturn($rv);
            }

            if($rs['userFlag'] == 1 && $rs['userStatus']==1){

                $data = array();
                $data['lastTime'] = date('Y-m-d H:i:s');
                $data['lastIP'] = get_client_ip();
                M("Users")->where(" userId=".$rs['userId'])->data($data)->save();




                //记录登录日志
                $data = array();
                $data["userId"] = $rs['userId'];
                $data["loginTime"] = date('Y-m-d H:i:s');
                $data["loginIp"] = get_client_ip();
                M('log_user_logins')->add($data);

                $rv = $rs;
                $v["shopInfo"] = array();
                if($rs["belongToShopId"]){
                    $shopInfo = M("Shops")->where(array("shopId"=>$rs["belongToShopId"]))->find();
                    $rv["shopInfo"] = $shopInfo;

                }else if($rs["userType"]==1){
                    $shopInfo = M("Shops")->where(array("userId"=>$rs['userId']))->find();
                    $rv["shopInfo"] = $shopInfo;
                }

                $rv["status"] = 1;
                $rv["msg"] = "登录成功";
            }else{
                $rv["msg"] = "请联系管理员启用该用户";

            }
        }else{
            $rv["msg"] = "该用户不存在";
        }
        $this->ajaxReturn($rv);

    }

    /**
     * 修改密码
     * userId,
     * newPwd，
     * code,
     * uniuqId
     *
     *
     */
    public function changePassword(){

        $result["status"] = 0;
        $code = M("Code")->field("code,createTime")->where(array("uniuqId"=>I("post.uniuqId")))->find();
        if(time() > strtotime('+5 min',intval($code["createTime"]))){
            $result["msg"] = "验证码超时";

        }else if($code["code"] != I("post.code")){
            $result["msg"] = "验证码无效";
        }else{
            $userId = I("post.userId");
            $data['userId'] = $userId;
            $rs = M("users")->field("loginPwd,loginSecret")->where(array("userId"=>$userId))->find();

            $newPwd = md5(I("post.newPwd").$rs["loginSecret"]);
            if($newPwd == $rs["loginPwd"]){
                $result["msg"] = "新密码不能和旧密码一样";
                $this->ajaxReturn($result);
            }
            M("users")->save(array("userId"=>$userId,"loginPwd"=>$newPwd));
            $result["msg"] = "修改成功";
            $result["status"] = 1;
        }


        $this->ajaxReturn($result);
    }


    /**
     * 重置密码
     *
     * userId
     * userPwd
     * newPwd
     */
    public function resetPassword(){
        $userId = I("post.userId");
        $user = M("users")->field("loginPwd,loginSecret")->where(array("userId"=>$userId))->find();
        $userPwd =  md5(I("post.userPwd").$user["loginSecret"]);
        $data["status"] = 0;
        if($user["loginPwd"] != $userPwd){
            $data["msg"] = "密码错误";
            $this->ajaxReturn($data);
        }

        $newPwd = md5(I("post.newPwd").$user["loginSecret"]);
        M("users")->save(array("userId"=>$userId,"loginPwd"=>$newPwd));
        $data["msg"] = "修改成功";
        $data["status"] = 1;
        $this->ajaxReturn($data);
    }


    /**
     * 消费记录
     * userId
     * pageNo
     * pageSize
     */

    function getPurchaseRecord(){
        $userId = I("post.userId");
        $pageNo = I("post.pageNo")-1;
        $pageSize = I("post.pageSize");
        $sql = <<<EOT
SELECT
	a.*, b.payName,
	CONCAT(MONTH(a.createTime),"月") AS m,
	CONCAT(YEAR (a.createTime),"年") AS y
FROM
	wst_log_moneys a
LEFT JOIN wst_payments b ON a.payType = b.id
WHERE
	a.targetId = $userId
ORDER BY
	createTime DESC
LIMIT $pageNo,
 $pageSize
EOT;

        $prList = M()->query($sql);
        $res = array();
        foreach($prList as $v){
            $res[$v['y']][$v['m']][] = $v;
        }

        array_multisort($res,SORT_DESC);

        $this->ajaxReturn($res);


    }



    /**
     * 投诉建议
     * userId
     * content
     */

    public function compliant(){
        $userId = I("post.userId");
        $content = I("post.content");
        $data["userId"] = $userId;
        $data["content"] = $content;
        $data["creatTime"] = time();
        $rs["status"] = 0;
        if( M("Complaint")->add($data)){
            $rs["status"] = 1;
        }

        $this->ajaxReturn($rs);

    }


    /**
     * 获取省份列表
     * areaId
     */
    public function getArea(){
        $areaId = I("post.areaId",0);

        $result = M("Areas")->field("areaId,areaName")->where(array("parentId"=>$areaId))->select();
        $this->ajaxReturn($result);
    }

    /**
     * 添加地址
     * areaId1,areaId2,areaId3,userName,userId,userPhone,address
     */

    function addAddress(){
        $m = M("UserAddress");

        $data["status"] = 0;
        if($m->create()){
            $m->addressFlag = 1;
            $m->createTime = date("Y-m-d H:i:s");
            if($m->add()){
                $data["status"] = 1;
            }
        }
        $this->ajaxReturn($data);
    }

    /**
     * 更新地址
     * addressId,areaId1,areaId2,areaId3,userName,userId,userPhone,address..............
     */
    function updateAddress(){
        $m = M("UserAddress");

        $data["status"] = 0;
        if($m->create()){
            if($m->save()){
                $data["status"] = 1;
            }
        }
        $this->ajaxReturn($data);
    }

    /**
     * 删除地址
     * $addressId
     * $userId
     */

    function delAddress(){
        $data["status"] = 0;
        $addressId = I("post.addressId");
        $userId = I("post.userId");
        if(M("UserAddress")->where(array("addressId"=>$addressId,"userId"=>$userId))->delete()){
            $data["status"] = 1;
        }

        $this->ajaxReturn($data);

    }

    /**
     * 获取用户地址列表
     * $userId
     */

    function getUserAddress(){
        $userId = I("post.userId");
        $sql = <<<EOT
SELECT
	a.*, b.areaName AS area1Name,
	c.areaName AS area2Name,d.areaName as area3Name

FROM
	wst_user_address a
LEFT JOIN wst_areas b ON a.areaId1 = b.areaId
LEFT JOIN wst_areas c ON a.areaId2 = c.areaId
LEFT JOIN wst_areas d ON a.areaId3 = d.areaId
WHERE
	userId = $userId
EOT;

        $addressList = M("UserAddress")->query($sql);
        $this->ajaxReturn($addressList);
    }


    /**
     * 更新用户信息
     * userName
     * userSex
     * userPhoto
     * userId
     */

    public function updateUserInfo(){
		$utils = new \Think\HYUtils();
        $userPhoto = $utils->uploadimg("Upload/users/", $_FILES["userPhoto"]);
		if($userPhoto == 'empty' || $userPhoto == 'toobig' || $userPhoto == 'errortype' || $userPhoto == 'moveerror')$userPhoto = null;
		
        $data["status"] = 0;
		$data['msg'] = "更新失败";
        $m = M("Users");
        if($m->create()){
            if($userPhoto != null){
                 $m->userPhoto = $userPhoto;
            }
            if($m->save()){
                $data["status"] = 1;
				$data['msg'] = "更新成功";
            }
        }
        $this->ajaxReturn($data);
    }


   /**
    * 搜索商家
    * $name
    * searchType
    */

    public function searchShop(){
        $name = I("post.name");
        $searchType = I("post.searchType",1);
        $searchList = null;
        $searchList = M("Shops")->where(array("shopName"=>array("like","%$name%"), "goodsCatId1"=>array('neq','7')))->select();
        $this->ajaxReturn($searchList);
    }

    /**
     * 获取支付方式列表
     */

    public function getPaymentList(){
        $result = M("Payments")->where(array("enabled"=>1))->order("payOrder")->select();
        $this->ajaxReturn($result);
    }


    /**
     * 添加订单

     * $userId
     * goodsId
     * goodsNums
     * goodsName
     * shopId
     * orderRemarks
     * invoiceClient     //发票抬头
     * isInvoice     //如果发票有发票需设置为1,否则为0
     *payType
     *  *goodsList:[{"goodsId":235,"goodsNums":5},{"goodsId":236,"goodsNums":5}............]
     * ********根据登录返回的商家数据里返回的isInvoice字段 值为1表示该商家提供开具发票、0表示不提供开具发票
     *     */

    function submitOrder(){
        $m = M("Orders");
        $ogm = M("OrderGoods");
        $gm = M("Goods");
        $goodsList = json_decode($_POST["goodsList"]);
        $result["status"] = 0;

        if($m->create()){
            foreach($goodsList as $v){
                $goodsIdList[] = $v->goodsId;
                $goodsNumsList[] = $v->goodsNums;
            }
            $goodsList = $gm->field("goodsName,goodsId,goodsThums,shopPrice,marketPrice")->where(array("goodsId"=>array("in",$goodsIdList)))->select();
            $totalMoney = 0;
            $realTotalMoney = 0;
            foreach($goodsList as $k=>$v){
                $tp = $v["shopPrice"];
                $totalMoney += $tp*$goodsNumsList[$k];
                $realTotalMoney += $v["shopPrice"]*$goodsNumsList[$k];
            }
            $m->totalMoney = $totalMoney;
            $m->realTotalMoney = $realTotalMoney;
            $m->orderunique = uniqid(true);
            $m->createTime = date("Y-m-d H:i:s");
            $m->orderStatus = 0;
            $m->orderNo = uniqid(true);
            if( I("post.invoiceClient")){
                $m->isInvoice = I("post.isInvoice");
                $m->invoiceClient = I("post.invoiceClient");
            }
            $result['orderNo'] = $m->orderNo;
            $result['totalMoney'] = $m->totalMoney;
            if( $orderId=$m->add()){
                foreach($goodsList as $k=>$v){
                    $data["goodsName"] = $v["goodsName"];
                    $data["goodsThums"] = $v["goodsThums"];
                    $data["goodsNums"] = $goodsNumsList[$k];
                    $data["goodsPrice"] = $v["shopPrice"];
                    $data["goodsId"] = $v["goodsId"];
                    $data["orderId"] = $orderId;
                    if($ogm->add($data)){
                        $result["status"] = 1;
                    }else{
                        $result["status"] = 0;
                    }
                }

            }else{
                $result["status"] = 0;
            }
        }

        $this->ajaxReturn($result);
    }


    /**
     * 获取用户订单列表
     * userId
     * orderType  0/1
     */

    public function getUserOrderList(){
        $userId = I("post.userId");
        $orderType = I("post.orderType",5);
        $shopId = I("post.shopId");

        $sql = <<<EOT
SELECT
	a.orderId,a.orderStatus,b.shopName,a.shopId,a.totalMoney,a.orderNo,a.createTime
FROM
	wst_orders a
LEFT JOIN wst_shops b ON a.shopId = b.shopId
WHERE
	orderFlag = 1
EOT;
       if($userId){
           $sql .= " AND a.userId = $userId";
       }else{
           $sql .= " AND a.shopId = $shopId";
       }



        if($orderType == 0 || $orderType == 1){
            $sql .= " AND orderStatus = $orderType ";
        }else if($orderType ==  3){
            $sql .= " AND orderStatus = 2 AND isAppraises = 0";
        }

        $sql .= " ORDER BY orderId DESC";
        $result = M()->query($sql);
        foreach($result as &$v){
            $orderGoodsList = M("OrderGoods")->where(array("orderId"=>$v["orderId"]))->select();
            $v["goodsList"] = $orderGoodsList;
        }
        $this->ajaxReturn($result);
    }

    /**
     * 支付订单
     * userId
     * orderId
     */
    function payOrder(){
        $userId = I("post.userId");
        $orderId = I("post.orderId");
        $data["status"] = 0;
        if(M("Orders")->where(array("userId"=>$userId,"orderId"=>$orderId))->setField("orderStatus",1)){
            $data["status"] = 1;
        }
        $this->ajaxReturn($data);
    }


    /**
     * 评论
     * orderId
     * shopId
     * userId
     * content
     */
    function appraise(){
        $data["status"] = 0;
        $m = M("GoodsAppraises");
        if($m->create()){
            $m->createTime = date("Y-m-d H:i:s");
            if($m->add()){
               if( M("Orders")->where(array("orderId"=>I("post.orderId")))->setField("isAppraises",1)){
                   $data["status"] = 1;
               }
            }
        }
        $this->ajaxReturn($data);
    }

    /********************
     * 获取城市列表，首页选需市用
     */
    function getCitys()
    {
        $City = M("areas");
        $citys = $City->field("areaId as id, areaName as name")->where("parentId in (select areaId from wst_areas where parentId = 0)")->select();
        $this->ajaxReturn($citys);
    }


    /**
     * 获取系统消息
     * userId
     * pageNo
     * pageSize
     */
    public function getSysMsg(){
        $userId = I("post.userId");
        $pageNo = I("post.pageNo")-1;
        $pageSize = I("post.pageSize");
        $sql = "select * from wst_messages where receiveUserId = $userId ORDER BY msgStatus ,createTime desc limit $pageNo ,$pageSize";
        $msgList = M()->query($sql);
        $this->ajaxReturn($msgList);
    }


    /**
     * 设置系统消息为已读
     * userId
     * id
     */
    public function ReadSysMsg(){
        $userId = I("post.userId");
        $id = I("post.id");
        $data["status"] = 0;
        if(M("Messages")->where(array("receiveUserId"=>$userId,"id"=>$id))->setField("msgStatus",1)){
            $data["status"] = 1;
        }
        $this->ajaxReturn($data);
    }

    /**
     * 删除消息
     * userId
     * id
     */

    public function delSysMsg(){
        $id = I("post.id");
        $userId = I("post.userId");
        $data["status"] = 0;
        if(M("Messages")->where(array("receiveUserId"=>$userId,"id"=>$id))->delete()){
            $data["status"] = 1;
        }
        $this->ajaxReturn($data);
    }


    /**
     * 获取银行列表
     */
    public function getBankList(){
        $this->ajaxReturn(D("Banks")->queryByList());
    }

    /**
     * 绑定银行卡/支付宝
     * userId
     * accTargetId   银行绑定的话需要，为银行列表中某银行Id
     * accNo      账号
     * accUser    绑定人
     * accType    1/3  支付宝/银行卡
     */
    public  function bindBankCart(){

        $m = M("CashConfigs");
        $data["status"] = 0;
        $accType = I("post.accType",3);
        if(!(M("users")->where(array("userId"=>I("post.userId")))->find())){
            $data["msg"] = "用户不存在";
            $this->ajaxReturn($data);
        }

        if($m->where(array("accNo"=>I("post.accNo")))->find()){
            $data["msg"] = "该支付账号已存在";
            $this->ajaxReturn($data);
        }

        if($accType == 3 ){
            $m->accTargetId = I("post.accTargetId");
        }
        $m->userId = I("post.userId");

        $m->accNo = I("post.accNo");
        $m->accUser = I("post.accUser");
        $m->accType = $accType;
        $m->areaId2 = 450600;
        $m->dataFlag = 1;
        $m->createTime = date("Y-m-d H:i:s");

        if($m->add()){
            $data["status"] = 1;
        }
        $this->ajaxReturn($data);
    }


    /**
     * 获取绑定支付宝或银行卡列表
     * userId
     */

    public function getBankCartList(){
        $userId = I("post.userId");
        $result = M("CashConfigs")->join("left join wst_banks on wst_cash_configs.accTargetId = wst_banks.bankId")->
        where(array("userId"=>$userId))->field("wst_cash_configs.* ,wst_banks.bankName")->select();
        $data = array();
        foreach($result as $v){

            $v["accType"] = intval($v["accType"]);
            if($v["accType"] == 3){
                $data[$v["accType"]][] = $v;
            }elseif($v["accType"] == 1){
                $data["zfb"] = $v;
            }

        }

        $this->ajaxReturn($data);

    }


    /**
     * 设置支付密码
     * payPwd
     * userPwd
     * userId
     */

    public function setPayPwd(){
        $rs["status"] = 0;
        $userId = I("post.userId");
        $userPwd = I("post.userPwd");
        $payPwd = I("post.payPwd");
        $m = M("users");
        $user = $m->where(array("userId"=>$userId))->field("loginPwd,loginSecret")->find();
        if( $user["loginPwd"]!=md5($userPwd.$user['loginSecret'])){
            $rs["msg"] = "密码错误";
            $this->ajaxReturn($rs);
        }

        $data["payPwd"]=md5($payPwd.$user["loginSecret"]);
        if($m->where(array("userId"=>$userId))->save($data)){
            $rs["status"]=1;
        }

        $this->ajaxReturn($rs);
    }



    /**
     * 商家资金提现
     * 支付密码  payPwd
     *  userId
     * configId  提现银行/支付宝账号
     * drawMoney  提现金额
     */


    public function shopDrawCash(){

        $userId = I("userId");
        $shopId = M("Shops")->where(array("userId"=>$userId))->getField("shopId");
        $rd = array('status'=>0);
        //验证支付密码
        $payPwd = I('post.payPwd');
        if(empty($payPwd)){
            $rd['msg'] = '请输入支付密码';
            $this->ajaxReturn($rd);
        }
        $sql = "select payPwd,loginSecret from __PREFIX__users where userId=".$userId;
        $user = M()->query($sql);
        if($user[0]['payPwd']!=md5(I("post.payPwd").$user[0]['loginSecret'])){
            $rd['msg'] = '支付密码不正确';
            $this->ajaxReturn($rd);
        }
        //获取提现账号信息
        if((int)I('configId')==0){
            $rd['msg'] = '请选择提现账号!';
            $this->ajaxReturn($rd);
        }
        $sql = "select l.*,b.bankName from __PREFIX__cash_configs l
		         left join __PREFIX__banks b on l.accTargetId=b.bankId
		         where l.dataFlag=1 and l.userId=".$userId." and l.id=".(int)I('post.configId');
        $config =  M()->query($sql);
        if(empty($config)){
            $rd['msg'] = '对不起,您的提现账号不存在!';
            $this->ajaxReturn($rd);
        }
        $money = (double)I('drawMoney');
        if($money<=0){
            $rd['msg'] = '提现金额必须大于0!';
            $this->ajaxReturn($rd);
        }
        //判断提现金额是否允许
        $sql = "select shopMoney from __PREFIX__shops where shopId=".$shopId;
        $shop = M()->query($sql);
        if($shop[0]['shopMoney']<$money){
            $rd['msg'] = '对不起，您的可提现金额不足!';
            $this->ajaxReturn($rd);
        }
        if($GLOBALS['CONFIG']['cashStartMoney']>$money){
            $rd['msg'] = '对不起，最低提现金额'.$GLOBALS['CONFIG']['cashStartMoney'].'元';
            $this->ajaxReturn($rd);
        }
        $cashModel = M("CashDraws");
        $cashModel->targetType = 1;
        $cashModel->targetId = $shopId;
        $cashModel->money = $money;
        $cashModel->accType = $config[0]['accType'];
        $cashModel->accTargetId = $config[0]['accTargetId'];
        $cashModel->accNo = $config[0]['accNo'];
        $cashModel->accUser = $config[0]['accUser'];
        $cashModel->cashSatus = 0;
        $cashModel->createTime = date('Y-m-d H:i:s');
        $cashModel->cashConfigId = (int)I('configId');
        $id =$cashModel->add();
        if(false !== $id){
            $data = array();
            $m = M('messages');
            $data["msgType"] = 0;
            $data["sendUserId"] = 0;
            $data["receiveUserId"] = $userId;
            $data["msgContent"] = "商家您申请提现 ¥".$money."已提交，预计明天24点前到帐！";
            $data["msgStatus"] = 0;
            $data["msgFlag"] = 1;
            $data["createTime"] = date('Y-m-d H:i:s');
            $m->add($data);
            $rd['status']= 1;
            $sql="update __PREFIX__shops set shopMoney=shopMoney-".$money.",lockMoney=lockMoney+".$money." where shopId=".$shopId;
            M()->execute($sql);
        }
        $this->ajaxReturn($rd);
    }


    /**
     * 用户资金提现
     * 支付密码  payPwd
     *  userId
     * configId  提现银行/支付宝账号
     * drawMoney  提现金额
     */

    public  function userDrawCash(){
        $userId = I("post.userId");
        $rd = array('status'=>0);
        //验证支付密码
        $payPwd = I('post.payPwd');
        if(empty($payPwd)){
            $rd['msg'] = '请输入支付密码';
            $this->ajaxReturn($rd);
        }
        $sql = "select userMoney,payPwd,loginSecret from __PREFIX__users where userId=".$userId;
        $user = M()->query($sql);
        if($user[0]['payPwd']!=md5(I("post.payPwd").$user[0]['loginSecret'])){
            $rd['msg'] = '支付密码不正确';
            $this->ajaxReturn($rd);
        }
        //获取提现账号信息
        if((int)I('configId')==0){
            $rd['msg'] = '请选择提现账号!';
            $this->ajaxReturn($rd);
        }
        $sql = "select l.*,b.bankName from __PREFIX__cash_configs l
		         left join __PREFIX__banks b on l.accTargetId=b.bankId
		         where l.dataFlag=1 and l.userId=".$userId." and l.id=".(int)I('configId');
        $config =  M()->query($sql);
        if(empty($config)){
            $rd['msg'] = '对不起,您的提现账号不存在!';
            $this->ajaxReturn($rd);
        }
        $money = (double)I('post.drawMoney');
        if($money<=0){
            $rd['msg'] = '提现金额必须大于0!';
            $this->ajaxReturn($rd);
        }
        //判断提现金额是否允许
        if($user[0]['userMoney']<$money){
            $rd['msg'] = '对不起，您的可提现金额不足!';
            $this->ajaxReturn($rd);
        }
        if($GLOBALS['CONFIG']['cashStartMoney']>$money){
            $rd['msg'] = '对不起，最低提现金额'.$GLOBALS['CONFIG']['cashStartMoney'].'元';
            $this->ajaxReturn($rd);
        }
        $cashModel = M("CashDraws");
        $cashModel->targetType = 0;
        $cashModel->targetId = $userId;
        $cashModel->money = $money;
        $cashModel->accType = $config[0]['accType'];
        $cashModel->accTargetId = $config[0]['accTargetId'];
        $cashModel->accNo = $config[0]['accNo'];
        $cashModel->accUser = $config[0]['accUser'];
        $cashModel->cashSatus = 0;
        $cashModel->createTime = date('Y-m-d H:i:s');
        $cashModel->cashConfigId = (int)I('configId');
        $id = $cashModel->add();
        if(false !== $id){
            $data = array();
            $m = M('messages');
            $data["msgType"] = 0;
            $data["sendUserId"] = 0;
            $data["receiveUserId"] = $userId;
            $data["msgContent"] = "买家您申请提现 ¥".$money."已提交，预计明天24点前到帐！";
            $data["msgStatus"] = 0;
            $data["msgFlag"] = 1;
            $data["createTime"] = date('Y-m-d H:i:s');
            $m->add($data);
            $rd['status']= 1;
            $sql="update __PREFIX__users set userMoney=userMoney-".$money.",lockMoney=lockMoney+".$money." where userId=".$userId;
            M()->execute($sql);
        }
        $this->ajaxReturn($rd);
    }


    /**
     * 获取养生或KTV的商品的时段价格
     * goodsId
     */
    public  function getPeriodPrice(){
        $goodsId = I("post.goodsId");
        $resultList = M("price")->where(array("goodsId"=>$goodsId))->select();
        $priceList = array();
        foreach($resultList as $v){
            $priceList[$v["weekDate"]][] = $v;
        }

        $this->ajaxReturn($priceList);
    }


    public function getCircles()
    {
        $pos = I("post.pos");
        $Circle = M("circles");
        $CircleImage = M("circle_images");
        $CircleComment = M("circle_comment");
        $User = M("users");
        $circles = $Circle->where("is_del = 0")->order("createtime desc")->limit("".$pos.", 10")->select();
        for($i = 0; $i < count($circles); $i++)
        {
            $user = $User->field("userId, loginName, userName, userPhoto")->where("userId = ".$circles[$i]['userid'])->find();
            $circles[$i]['user'] = $user;
            $images = $CircleImage->where("circleid = ".$circles[$i]['id']." and is_del = 0")->select();
            $circles[$i]['images'] = $images;
            $comments = $CircleComment->where("circleid = ".$circles[$i]['id']." and is_del = 0")->select();
            for($m = 0; $m < count($comments); $m++)
            {
                $u = $User->field("userId, loginName, userName, userPhoto")->where("userId = ".$comments[$m]['userid'])->find();
                $comments[$m]['user'] = $u;
            }
            $circles[$i]['comments'] = $comments;
        }
        $this->ajaxReturn($circles);
    }

    public function getMyCircles()
    {
        $pos = I("post.pos");
        $userid = I("post.userId");
        $Circle = M("circles");
        $CircleImage = M("circle_images");
        $CircleComment = M("circle_comment");
        $User = M("users");
        $circles = $Circle->where("(userid in (select friendid from wst_user_friends where userid = ".$userid.") or userid = ".$userid.") and is_del = 0")->order("createtime desc")->limit("".$pos.", 10")->select();
        for($i = 0; $i < count($circles); $i++)
        {
            $user = $User->field("userId, loginName, userName, userPhoto")->where("userId = ".$circles[$i]['userid'])->find();
            $circles[$i]['user'] = $user;
            $images = $CircleImage->where("circleid = ".$circles[$i]['id']." and is_del = 0")->select();
            $circles[$i]['images'] = $images;
            $comments = $CircleComment->where("circleid = ".$circles[$i]['id']." and is_del = 0")->select();
            for($m = 0; $m < count($comments); $m++)
            {
                $u = $User->field("userId, loginName, userName, userPhoto")->where("userId = ".$comments[$m]['userid'])->find();
                $comments[$m]['user'] = $u;
            }
            $circles[$i]['comments'] = $comments;
        }
        $this->ajaxReturn($circles);
    }

    public function addCircle()
    {
        $userid = I("post.userId");
        $content = I("post.content");
        $utils = new \Think\HYUtils();
        $image1 = $utils->uploadimg("Upload/circles/", $_FILES["image1"]);
        if($image1 == 'empty' || $image1 == 'toobig' || $image1 == 'errortype' || $image1 == 'moveerror')$image1 = null;
        else $images[] = $image1;
        $image2 = $utils->uploadimg("Upload/circles/", $_FILES["image2"]);
        if($image2 == 'empty' || $image2 == 'toobig' || $image2 == 'errortype' || $image2 == 'moveerror')$image2 = null;
        else $images[] = $image2;
        $image3 = $utils->uploadimg("Upload/circles/", $_FILES["image3"]);
        if($image3 == 'empty' || $image3 == 'toobig' || $image3 == 'errortype' || $image3 == 'moveerror')$image3 = null;
        else $images[] = $image3;
        $image4 = $utils->uploadimg("Upload/circles/", $_FILES["image4"]);
        if($image4 == 'empty' || $image4 == 'toobig' || $image4 == 'errortype' || $image4 == 'moveerror')$image4 = null;
        else $images[] = $image4;
        $Circle = M("circles");
        $CircleImage = M("circle_images");
        $c["userid"] = $userid;
        $c['content'] = $content;
        $c['read']= 0;
        $c['createtime'] = time();
        $c['is_del'] = 0;
        if($Circle->add($c))
        {
            $c = $Circle->where("userid = ".$userid." and createtime = ".$c['createtime'])->order("createtime desc")->find();
            for($i = 0; $i < count($images); $i++)
            {
                $image['circleid'] = $c['id'];
                $image['image'] = $images[$i];
                $image['is_del'] = 0;
                $CircleImage->add($image);
            }
            $rs['status'] = 0;
            $rs['msg'] = "发表成功！";
            $this->ajaxReturn($rs);
        }
        else
        {
            $rs['status'] = 1;
            $rs['msg'] = "发表失败！";
            $this->ajaxReturn($rs);
        }
    }

    public function delCircle()
    {
        $userid = I("post.userId");
        $circleid = I("post.circleid");
        $Circle = M("circles");
        $c = $Circle->where("id = ".$circleid." and userid = ".$userid)->find();
        $c['is_del'] = 1;
        if($Circle->save($c))
        {
            $rs['status'] = 0;
            $rs['msg'] = "删除成功！";
            $this->ajaxReturn($rs);
        }
        else
        {
            $rs['status'] = 1;
            $rs['msg'] = "删除失败！";
            $this->ajaxReturn($rs);
        }
    }



    /**
     * 养生服务员获取服务列表
     * shopId
     * serviceStatus  **** 服务状态  **** -1/0/2/3   ******全部/未接/已接/完成
     */

    public function getHealthService(){
        $shopId = I("post.shopId");
        $sql = <<<EOT
SELECT
	a.orderId, b.shopName,c.userName,c.userPhone,d.goodsName,d.goodsPrice,a.appointment,a.dropInAddress,a.serviceStatus
FROM
	wst_orders a
LEFT JOIN wst_shops b ON a.shopId = b.shopId
LEFT JOIN wst_users c on a.userId = c.userId
left join wst_order_goods d on a.orderId = d.orderId

WHERE
	a.shopId = $shopId
AND orderStatus = 2
EOT;


        $serviceStatus = I("post.serviceStatus");
        switch($serviceStatus){
            case -1:
                break;
            case 0:
                $sql .= " and serviceStatus = 0";
                break;
            case 1:
                $sql .= " and serviceStatus between 1 and 7";
                break;
            case 2:
                $sql .= " and serviceStatus = 7";
        }

        $resultList = M()->query($sql);
        $this->ajaxReturn($resultList);

    }


    /**
     * ***养生商家服务员接/完成服务流程
     * ****waiterId   ***** 当前登录的服务员Id  既userId*****
     * ***orderId   *****服务Id
     * ***lat      *****接单时纬度      *****上门服务时需要******
     * ****lng        *****接单时经度     *****上门服务需要*******
     * ***serviceStatus  **** 当前服务状态 **** 服务状态  1/2/3/4/5/6/7   ****接单/出发/到达/开始服务/结束服务/返回/完成服务
     */
    public function changeServiceStatus(){
        $data["status"] = 0;
        $orderId = I("post.orderId");
        $serviceStatus = I("post.serviceStatus");
        $m = M("HealthService");
        if($m->create()){
            $m->statusTime = date("Y-m-d H:i:s");
            $m->serviceStatus = $serviceStatus;
            if($m->add()){
                if(M("Orders")->where(array("orderId"=>$orderId))->setField("serviceStatus",$serviceStatus)){
                    $data["status"] = 1;
                }
            }
        }
        $this->ajaxReturn($data);
    }


    /**
     * 获取服务会员某服务接单状态
     * ** waiterId***  服务员Id
     * ** orderId *** 服务订单Id
     */

    public  function getWaiterServiceStatus(){
        $waiterId = I("post.waiterId");
        $orderId = I("post.orderId");
        $statusList = M("HealthService")->where(array("waiterId"=>$waiterId,"orderId"=>$orderId))->select();
        $this->ajaxReturn($statusList);
    }



    /**
     * 客户端申请退款
     * orderId
     * userId
     */

    public function refundOrder(){
        $data["status"] = 0;
        if(M("Orders")->where(array("orderId"=>I("post.orderId"),"userId"=>I("post.userId")))->
        save(array("isRefund"=>1,"refundApplyTime"=>date("Y-m-d H:i:s"),"orderStatus"=>3))){
            $data["status"] = 1;
        }
        $this->ajaxReturn($data);
    }


    /**
     * 服务端确定退款
     * orderId
     * shopId
     * refundRemark
     */
    public function confirmRefund(){
        $data["status"] = 0;
        if(M("Orders")->where(array("orderId"=>I("post.orderId"),"shopId"=>I("post.shopId")))->
        save(array("isRefund"=>2,"refundRemark"=>I("post.refundRemark"),"orderStatus"=>3,"refundConfirmTime"=>date("Y-m-d H:i:s"),))){
            $data["status"] = 1;
        }

        $this->ajaxReturn($data);
    }



    /**
     * 获取套餐
     * lat  纬度
     * lng  经度
     * pageNo
     * pageSize
     */


    public  function getPackageList(){
        $pageNo = I("post.pageNo",1);
        $pageSize = I("post.pageSize",10);
        $packageModel = M("taocans");
        $where = array();
        if($tName = I("post.tName")){
            $where["tName"] = array("like","%$tName%");
        }

        if($shopName = I("post.shopName")){
            $where["shopName"] = array("like","%$shopName%");
        }

        if($goodsName = I("post.goodsName")){
            $where["goodsName"] = array("like","%$goodsName%");
        }

        $where["is_del"] = 0;

        $pList = $packageModel->join("join wst_taocan_goods on wst_taocans.id = wst_taocan_goods.tId")
            ->join("join wst_goods on wst_taocan_goods.goodsId = wst_goods.goodsId")
            ->join("join wst_shops on wst_goods.shopId = wst_shops.shopId")
            ->field("distinct(wst_taocans.id) as tId,wst_taocans.
             price,tName")
            ->where($where)->order("tId desc")->limit(($pageNo-1).",".$pageSize)->select();
        $tGoodsModel = M("TaocanGoods");
        foreach($pList as &$pItem){
            $goodsList = $tGoodsModel->join("join  wst_goods on wst_taocan_goods.goodsId = wst_goods.goodsId")
                ->join("join wst_shops on wst_shops.shopId = wst_goods.shopId")->where(array("tId"=>$pItem["tId"]))
                ->field("wst_goods.goodsId,goodsName,shopPrice,goodsSpec,wst_shops.shopName,goodsThums,tPrice")->select();
            $pItem["goods"] = $goodsList;
        }
        $this->ajaxReturn($pList);
    }



    /**
     * 获取商家商品相关套餐
     * goodsId
     * pageNo
     * pageSize
     */


    public  function getShopGoodsPackage(){
        $pageNo = I("post.pageNo",1);
        $pageSize = I("post.pageSize",10);
        $packageModel = M("taocans");
        $where = array();
        if($tName = I("post.tName")){
            $where["tName"] = array("like","%$tName%");
        }

        if($shopName = I("post.shopName")){
            $where["shopName"] = array("like","%$shopName%");
        }

        if($goodsName = I("post.goodsName")){
            $where["goodsName"] = array("like","%$goodsName%");
        }

        $where["is_del"] = 0;
        $where["wst_taocan_goods.goodsId"] = I("post.goodsId");


        $pList = $packageModel->join("join wst_taocan_goods on wst_taocans.id = wst_taocan_goods.tId")
            ->join("join wst_goods on wst_taocan_goods.goodsId = wst_goods.goodsId")
            ->join("join wst_shops on wst_goods.shopId = wst_shops.shopId")
            ->field("distinct(wst_taocans.id) as tId,wst_taocans.
             price,tName")
            ->where($where)->order("tId desc")->limit(($pageNo-1).",".$pageSize)->select();
        $tGoodsModel = M("TaocanGoods");
        foreach($pList as &$pItem){
            $goodsList = $tGoodsModel->join("join  wst_goods on wst_taocan_goods.goodsId = wst_goods.goodsId")
                ->join("join wst_shops on wst_shops.shopId = wst_goods.shopId")->where(array("tId"=>$pItem["tId"]))
                ->field("wst_goods.goodsId,goodsName,shopPrice,goodsSpec,wst_shops.shopName,goodsThums,tPrice")->select();
            $pItem["goods"] = $goodsList;
        }

        $this->ajaxReturn($pList?$pList:array());
    }



    




}